package com.kpf.springcloud.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.kpf.springcloud.common.ResponseEnum;
import com.kpf.springcloud.exception.BusinessException;
import com.kpf.springcloud.mapper.TopicCollectMapper;
import com.kpf.springcloud.mapper.TopicCommentMapper;
import com.kpf.springcloud.mapper.TopicMapper;
import com.kpf.springcloud.mapper.UserMapper;
import com.kpf.springcloud.pojo.KpfTopic;
import com.kpf.springcloud.pojo.KpfTopicCollect;
import com.kpf.springcloud.pojo.KpfUser;
import com.kpf.springcloud.pojo.PageResult;
import com.kpf.springcloud.service.IKpfTopicCollectService;
import com.kpf.springcloud.service.IKpfTopicService;
import com.kpf.springcloud.service.IKpfUserService;
import com.kpf.springcloud.service.ITokenService;
import com.kpf.springcloud.utils.GeneralUtil;
import com.kpf.springcloud.utils.Md5Utils;
import com.kpf.springcloud.vo.KpfUserTopicListVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.annotation.Resource;
import java.util.List;

/**
 * @author shiwen
 * @date 2021/2/16
 */
@Service
public class KpfUserServiceImpl extends BaseServiceImpl<UserMapper, KpfUser> implements IKpfUserService {

    private Logger logger = LoggerFactory.getLogger(KpfUserServiceImpl.class);

    @Resource
    private UserMapper userMapper;

    @Resource
    private TopicCommentMapper topicCommentMapper;

    @Resource
    private TopicMapper topicMapper;

    @Autowired
    private ITokenService tokenService;

    @Autowired
    private IKpfTopicService topicService;

    @Resource
    private TopicCollectMapper collectMapper;

    @Autowired
    private IKpfTopicCollectService kpfTopicCollectService;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public List<KpfUser> queryAll() {
        return userMapper.queryAll();
    }

    @Override
    public List<KpfUser> queryAll_mp() {
        return list(getInitQueryWrapper().eq(KpfUser::getId, 2));
    }

    /**
     * 注册账号接口
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean registerUser(Long age, String phone, String address, String username, String password) {
        KpfUser kpfUser = KpfUser.builder().sex(0).age(age).phone(phone).address(address).userType(0)
                .username(username).password(Md5Utils.setMD5(password)).build();
        boolean resultFlag = save(kpfUser);
        if (resultFlag) {
            // 保存成功的时候返回true
            return true;
        }
        return false;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public KpfUser login(String phone, String password) {
        return getOne(getInitQueryWrapper().eq(KpfUser::getPhone, phone).eq(KpfUser::getPassword, Md5Utils.setMD5(password)));
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean modifySelfInfo(String headimg, String username, String phone, String password, String address) {
        String token = tokenService.verifyToken();
        // 判断token是否过期
        if ("TOKEN_EXPIRED".equals(token)) {
            throw new BusinessException(ResponseEnum.TOKEN_EXPIRED);
        }
        int userId = Integer.parseInt(token.split("-")[0]);
        KpfUser oldUser = getById(userId);
        // 判断旧账号是否存在, 存在才进行修改
        if (GeneralUtil.isObjNull(oldUser)) {
            throw new BusinessException(ResponseEnum.USER_NOT_EXIST);
        }
        String newPassword = Md5Utils.setMD5(password);
        // 如果旧密码跟新密码一样, 就不需要改密码了
        if (oldUser.getPassword().equals(password)) {
            newPassword = oldUser.getPassword();
        }
        boolean resultFlag = update(getLambdaUpdateWrapper().set(KpfUser::getPhone, phone).set(KpfUser::getHeadimg, headimg)
                .set(KpfUser::getUsername, username).set(KpfUser::getPassword, newPassword)
                .set(KpfUser::getAddress, address).eq(KpfUser::getId, userId));
        if (resultFlag) {
            // 同步修改帖子中的头像和用户名
            topicService.update(topicService.getLambdaUpdateWrapper().set(KpfTopic::getUserName, username)
                    .set(KpfTopic::getUserImg, headimg).eq(KpfTopic::getUserId, userId));
            logger.info("Processing updateUser success！phone = {}", phone);
            // 保存成功的时候返回true
            return true;
        }
        return false;
    }

    @Override
    public KpfUser getLoginUserById() {
        String token = tokenService.verifyToken();
        // 判断token是否过期
        if ("TOKEN_EXPIRED".equals(token)) {
            throw new BusinessException(ResponseEnum.TOKEN_EXPIRED);
        }
        int userId = Integer.parseInt(token.split("-")[0]);
        // 获取登录的用户id
        return getById(userId);
    }

    /**
     * 设置userId到redis
     *
     * @param userId
     */
    @Override
    public void setSelfUserId(int userId) {
        stringRedisTemplate.opsForValue().set("kpf:selfUserId", userId + "");
    }

    /**
     * 根据用户id获取user对象和发布的帖子内容
     */
    @Override
    public KpfUserTopicListVO getByUserId() {
        String userId = stringRedisTemplate.opsForValue().get("kpf:selfUserId");
        // 这里如果userId为0的话可以直接去拿redis里面的userId
        if (GeneralUtil.isNotNullAndEmpty(userId)) {
            KpfUser kpfUser = getById(userId);
            List<KpfTopic> kpfTopicList = topicService.list(topicService.getInitQueryWrapper().eq(KpfTopic::getUserId, userId));
            KpfUserTopicListVO kpfUserTopicListVO = KpfUserTopicListVO.builder().kpfUser(kpfUser).kpfTopicList(kpfTopicList).build();
            return kpfUserTopicListVO;
        }
        return new KpfUserTopicListVO();
    }

    /**
     * 获取用户列表
     *
     * @param pageNum
     * @param pageSize
     * @return
     */
    @Override
    public PageResult userList(int pageNum, int pageSize) {
        Page page = PageHelper.startPage(pageNum, pageSize);
        // 不查管理员
        List<KpfUser> userList = list(getInitQueryWrapper().ne(KpfUser::getUserType, 3));
        return new PageResult(userList, page.getTotal(), pageNum, pageSize);
    }

    /**
     * 根据用户id删除用户对象
     *
     * @param userId
     */
    @Override
    public void deleteUserById(int userId) {
        String token = tokenService.verifyToken();
        // 判断token是否过期
        if ("TOKEN_EXPIRED".equals(token)) {
            throw new BusinessException(ResponseEnum.TOKEN_EXPIRED);
        }
        // 用户id
        int adminId = Integer.parseInt(token.split("-")[0]);
        // 角色类型
        int roleType = Integer.parseInt(token.split("-")[1]);
        // 管理员角色的type = 2
        if (roleType == 2) {
            userMapper.deleteById(userId);
            // 用户相关的评论和帖子都要删除
            topicCommentMapper.deleteByUserId(userId);
            topicMapper.deleteByUserId(userId);
            // 收藏信息也要删除
            collectMapper.delete(kpfTopicCollectService.getInitQueryWrapper().eq(KpfTopicCollect::getUserId, userId));
            logger.info("Processing delete topic success！adminId = {} , userId = {}", adminId, userId);
        } else {
            throw new BusinessException(ResponseEnum.NOT_ADMIN_USER_TO_OPERA);
        }
    }

}